package com.tiancikeji.zaoke.app.service.bill.impl.alipay;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.tiancikeji.zaoke.app.model.order.Bill;
import com.tiancikeji.zaoke.app.service.bill.impl.alipay.util.Rsa;

public class AlipayAppPayMent implements PayMent {

	public String getPayUrl(Bill bill, String system) {
		StringBuilder buf = new StringBuilder();
		addParam(buf, "_input_charset", "UTF-8");
		addParam(buf, "body", bill.getBody());
		addParam(buf, "notify_url", AlipayAppConfig.NOTIFY_URL);
		addParam(buf, "out_trade_no", bill.getSerialId());
		addParam(buf, "partner", AlipayAppConfig.PARTNER_ID);
		addParam(buf, "payment_type", "1");
		addParam(buf, "seller", AlipayAppConfig.SELLER_ID);
		addParam(buf, "service", AlipayAppConfig.SERVICE);

		addParam(buf, "subject", bill.getSubject());
		addParam(buf, "total_fee", String.format("%.2f", bill.getMoney()));

		//TODO
		//addParam(buf, "extern_token", StringUtils.EMPTY);

		String sign = sign(buf.toString());
		addParam(buf, "sign", sign);
		addParam(buf, "sign_type", "RSA");
		return buf.toString();
	}

	public void addParam(StringBuilder buf, String key, String value) {
		if (buf.length() != 0) {
			buf.append('&');
		}
		buf.append(key);
		buf.append("=");
		buf.append('"');
		buf.append(value);
		buf.append('"');
	}

	private String sign(String orderInfo) {
		try {
			return URLEncoder.encode(
					Rsa.sign(orderInfo, AlipayAppConfig.ZAOKE_PRIVATE), "utf8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("不可能没有utf8", e);
		}
	}
}
